package com.wangyi.im.interceptor;

import okhttp3.*;
import org.springframework.util.ReflectionUtils;

import java.io.IOException;

public class BodyInterceptor implements Interceptor {

    private Object body;

    public BodyInterceptor(Object body){
        this.body = body;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        FormBody.Builder requestBody = new FormBody.Builder();
        ReflectionUtils.doWithFields(body.getClass(), field -> {
            // 设置字段可反射
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            // 排除字段为空的情况
            if (field.get(body) == null) {
                return;
            }
            requestBody.add(field.getName(), field.get(body).toString());
        });
        return chain.proceed(request.newBuilder().post(requestBody.build()).build());
    }
}
